package com.xzp.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xzp.yygh.hosp.repository.DepartmentRepository;
import com.xzp.yygh.hosp.service.DepartmentService;
import com.xzp.yygh.model.hosp.Department;
import com.xzp.yygh.vo.hosp.DepartmentQueryVo;
import com.xzp.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 根据传入的json，添加科室信息到mongodb
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        // 类型转换： map -> string -> Department
        Department department = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Department.class);
        // 从mongodb中根据depcode以及hoscode获取department
        Department targetDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (null != targetDepartment) {
            // 数据存在则更新
            BeanUtils.copyProperties(department, targetDepartment, Department.class);
            departmentRepository.save(targetDepartment);
        } else {
            // 数据不存在 添加
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }


    }

    @Override
    public Page<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        // 按照创建时间降序排列
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //  0为第一页
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        // 将departmentQueryVo注入department
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Department> example = Example.of(department, matcher);
        // 就模糊查询的结果在进行分页展示
        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(null != department) {
        //departmentRepository.delete(department);
            departmentRepository.deleteById(department.getId());
        }
    }

    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        // 定义一个results存储每一级department的父子关系
        ArrayList<DepartmentVo> results = new ArrayList<>();
        Department department = new Department();
        department.setHoscode(hoscode);
        Example<Department> example = Example.of(department);
        // 从mongodb中找到所有depatment数据
        List<Department> departmentList = departmentRepository.findAll(example);
        // 根据bigcode对department进行分类
        Map<String, List<Department>> departmentMap = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        // 遍历每个类别
        for(Map.Entry<String, List<Department>> entry: departmentMap.entrySet()){
            DepartmentVo departmentVo = new DepartmentVo();
            String bigcode = entry.getKey();
            List<Department> departmentList1 = entry.getValue();
            departmentVo.setDepcode(bigcode);
            departmentVo.setDepname(departmentList1.get(0).getBigname());
            ArrayList<DepartmentVo> departChilds = new ArrayList<>();
            // 遍历每个子类，设置child信息
            for(Department depart: departmentList1){
                DepartmentVo departmentVo1 = new DepartmentVo();
                departmentVo1.setDepname(depart.getDepname());
                departmentVo1.setDepcode(depart.getDepcode());
                departChilds.add(departmentVo1);
            }
            departmentVo.setChildren(departChilds);
            results.add(departmentVo);
        }
        return results;
    }


    /**
     * 根据hoscode和deptcode获取部门名称
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public String getDeptName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        return department.getDepname();
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        return department;
    }


}
